import router from '@/router'
import { useUserStore } from '@/stores/user'
import axios, { type Method } from 'axios'
import { ElMessage } from 'element-plus/lib'

const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 20 * 1000,
})

// 后端返回类型
export interface ServiceResponse<T> {
  code: number
  msg: string
  data: T
}
export const request = <T>(url: string, method: Method = 'GET', submitData?: object) => {
  // 返回 Promise
  return service.request<T,ServiceResponse<T>>({
    url: url,
    method: method,
    // []  插值表达式 动态设置 对象的键名称
    // 请求参数：GET 请求用 params，否则用 data
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData
  })
}



service.interceptors.request.use(
  config => {
    // 获取 token
    const store = useUserStore()
    if(store.token){
      config.headers.Authorization = `Bearer ${store.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {

    if ( error.response) {
      ElMessage.error(error.response.data.msg)
      if(error.response.status === 401) {
        // 跳转登录页
        router.push("/login")
        // 清除token信息
        const store = useUserStore()
        store.clearToken()
      }
    }else {
      ElMessage.error("请求超时，请稍后再试")
    }
    return Promise.reject(error)
  },
)

export default service
